package com.bnlr.lrparking.wxapi;

import android.content.Intent;
import android.os.Bundle;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.appui.login.RegisterActivity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.SpConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.CloseLoginEvent;
import com.bnlr.lrparking.model.UserByWx;
import com.bnlr.lrparking.model.WXTokenResponse;
import com.bnlr.lrparking.model.WXUserInfoBean;
import com.bnlr.lrparking.model.WXUserResponse;
import com.bnlr.lrparking.model.WXVerifyAKResponse;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;

/**
 * 微信登录
 *
 * @author tian
 * @date 2017/11/2
 */
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private Gson gson;
    private WXUserInfoBean wxUserInfoBean;
    private String wxCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 微信事件回调接口注册
        Application.mWxApi.handleIntent(getIntent(), this);
        gson = new Gson();
        wxUserInfoBean = new WXUserInfoBean();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Application.mWxApi.handleIntent(intent, this);
    }

    /**
     * 登录微信
     */
    public static void loginWeiXin() {
        // 判断是否安装了微信客户端
        if (!Application.mWxApi.isWXAppInstalled()) {
            ToastUtils.showShort("您还未安装微信客户端！");
            return;
        }
        // 发送授权登录信息，来获取code
        SendAuth.Req req = new SendAuth.Req();
        // 应用的作用域，获取个人信息
        req.scope = "snsapi_userinfo";
        // 用于保持请求和回调的状态，授权请求后原样带回给第三方
        // 为了防止csrf攻击（跨站请求伪造攻击），后期改为随机数加session来校验
        req.state = "app_wechat";
        Application.mWxApi.sendReq(req);
    }

    /**
     * 微信发送请求到第三方应用时，会回调到该方法
     *
     * @param req req
     */
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:

                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            default:
                break;
        }
        finish();
    }

    /**
     * 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
     *
     * @param resp resp
     */
    @Override
    public void onResp(BaseResp resp) {

        LogUtils.i("resp.errCode", resp.errCode, "resp.errStr", resp.errStr, "resp.openId", resp.openId, "resp.transaction", resp.transaction);
        switch (resp.errCode) {
            // 发送成功
            case BaseResp.ErrCode.ERR_OK:
                // 获取code
                String code = ((SendAuth.Resp) resp).code;
                wxCode = code;
                // 通过code获取授权口令access_token
                String wxOpenid = AppConfig.getInstance().getString(SpConstant.KEY_WX_OPENID, null);
                String wxAccessToken = AppConfig.getInstance().getString(SpConstant.KEY_WX_ACCESS_TOKEN, null);
                String wxUnionid = AppConfig.getInstance().getString(SpConstant.KEY_WX_UNIONID, null);
                if (wxOpenid == null || wxAccessToken == null || wxUnionid == null) {
                    getAccessToken(code);
                } else {
                    getAccessTokenValid(wxOpenid, wxAccessToken, wxUnionid);
                }
                break;
            default:
                EventBus.getDefault().post(new CloseLoginEvent(2));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 根据code获取access_token
     *
     * @param code code
     */
    private void getAccessToken(String code) {

        HttpParams params = new HttpParams();
        params.put("appid", LrConstant.WX_APP_ID);
        params.put("secret", LrConstant.WX_APP_SECRET);
        params.put("code", code);
        params.put("grant_type", LrConstant.WX_GRANT_TYPE);

        OkGo.<String>post(Urls.WX_GET_ACCESS_TOKEN)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.body() != null) {
                            WXTokenResponse wxTokenResponse = gson.fromJson(response.body(), WXTokenResponse.class);
                            AppConfig.getInstance().putString(SpConstant.KEY_WX_ACCESS_TOKEN, wxTokenResponse.getAccess_token());
                            AppConfig.getInstance().putString(SpConstant.KEY_WX_OPENID, wxTokenResponse.getOpenid());
                            AppConfig.getInstance().putString(SpConstant.KEY_WX_UNIONID, wxTokenResponse.getUnionid());
                            LogUtils.i("wxTokenResponse", wxTokenResponse.toString());
                            getUserInfo(wxTokenResponse.getOpenid(), wxTokenResponse.getAccess_token(), wxTokenResponse.getUnionid());
                        }
                    }
                });
    }


    /**
     * 获取微信用户信息
     *
     * @param openid      openid
     * @param accessToken accessToken
     */
    private void getUserInfo(final String openid, final String accessToken, final String unionid) {

        HttpParams params = new HttpParams();
        params.put("access_token", accessToken);
        params.put("openid", openid);

        OkGo.<String>get(Urls.WX_GET_USER_INFO)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.body() != null) {
                            WXUserResponse wxUserResponse = gson.fromJson(response.body(), WXUserResponse.class);

                            wxUserInfoBean.setCountry(wxUserResponse.getCountry());
                            wxUserInfoBean.setProvince(wxUserResponse.getProvince());
                            wxUserInfoBean.setCity(wxUserResponse.getCity());
                            wxUserInfoBean.setNickname(wxUserResponse.getNickname());
                            wxUserInfoBean.setSex(wxUserResponse.getSex());
                            wxUserInfoBean.setHeadimgurl(wxUserResponse.getHeadimgurl());
                            LogUtils.i("wxUserInfoBean", wxUserInfoBean.toString());

                            wxUserLogin(wxUserResponse.getNickname(), wxUserResponse.getHeadimgurl(), openid, unionid);

                        }
                    }
                });
    }

    /**
     * 判断access token 是否有效
     *
     * @param openid      openid
     * @param accessToken accessToken
     */
    private void getAccessTokenValid(final String openid, final String accessToken, final String unionid) {

        HttpParams params = new HttpParams();
        params.put("access_token", accessToken);
        params.put("openid", openid);

        OkGo.<String>get(Urls.WX_VERIFY_ACCESS_TOKEN)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.body() != null) {
                            WXVerifyAKResponse wxVerifyAKResponse = gson.fromJson(response.body(), WXVerifyAKResponse.class);
                            if (wxVerifyAKResponse.getErrcode() == 0) {
                                getUserInfo(openid, accessToken, unionid);
                            } else {
                                getAccessToken(wxCode);
                            }
                        }
                    }
                });

    }

    /**
     * 微信用户登录
     */
    private void wxUserLogin(String nickname, String headimgurl, String openid, String unionid) {
        HttpParams params = new HttpParams();
        params.put("nickname", nickname);
        params.put("headimgurl", headimgurl);
        params.put("openid", openid);
        params.put("unionid", unionid);
        params.put("phonePara", Application.DEVICE_ID);

        OkGo.<String>post(Urls.URL_WX_USER_LOGIN)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        UserByWx userByWx = gson.fromJson(response.body(), UserByWx.class);
                        LogUtils.e("userByWx", userByWx.toString());

                        if (userByWx.getMsgcode() == 1) {

                            if (userByWx.getData().getUserName().isEmpty()) {
                                // 手机号为空，绑定手机号
                                EventBus.getDefault().post(new CloseLoginEvent(1));
                            } else {
                                AppConfig.getInstance().putBoolean("isLogin", true);
                                AppConfig.getInstance().putBoolean(SpConstant.KEY_IS_WX_LOGIN, true);
                                AppConfig.getInstance().putString("uid", String.valueOf(userByWx.getData().getUid()));
                                AppConfig.getInstance().putString("userName", userByWx.getData().getUserName());
                                AppConfig.getInstance().putString("nickName", userByWx.getData().getNickName());
                                AppConfig.getInstance().putString("realName", userByWx.getData().getRealName());
                                AppConfig.getInstance().putString("password", userByWx.getData().getPassword());
                                AppConfig.getInstance().putString("salt", userByWx.getData().getSalt());
                                AppConfig.getInstance().putString("photo", userByWx.getData().getPhoto());
                                AppConfig.getInstance().putString("paypassword", userByWx.getData().getPaypassword());
                                AppConfig.getInstance().putString("status", String.valueOf(userByWx.getData().getStatus()));
                                AppConfig.getInstance().putString("sharevalue", String.valueOf(userByWx.getData().getSharevalue()));
                                AppConfig.getInstance().putString("sharevalue_u", String.valueOf(userByWx.getData().getSharevalue_u()));
                                AppConfig.getInstance().putString("parktime", String.valueOf(userByWx.getData().getParktime()));
                                AppConfig.getInstance().putString("incomevalue", String.valueOf(userByWx.getData().getIncomevalue()));
                                AppConfig.getInstance().putString("isRealNameAuth", String.valueOf(userByWx.getData().getIsRealNameAuth()));
                                AppConfig.getInstance().putString("idcard", userByWx.getData().getIdcard());
                                AppConfig.getInstance().putString("sex", String.valueOf(userByWx.getData().getSex()));
                                // 发送通知
                                EventBus.getDefault().post(new CloseLoginEvent(3));
                                // 设置极光推送别名
                                JPushInterface.setAlias(getApplicationContext(), 2019, userByWx.getData().getUserName());
                            }

                        } else {
                            EventBus.getDefault().post(new CloseLoginEvent(2));
                        }
                        finish();
                    }
                });

    }

}
